package rjgc.mall.controller;

import org.apache.ibatis.annotations.DeleteProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import rjgc.mall.common.MessageConstant;
import rjgc.mall.common.MySessionContext;
import rjgc.mall.common.Result;
import rjgc.mall.entity.*;
import rjgc.mall.entity.vo.RegisterParam;
import rjgc.mall.mapper.TradeActionMapper;
import rjgc.mall.service.OrderService;
import rjgc.mall.service.SellerService;
import rjgc.mall.service.UserService;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/seller")
public class SellerController {
    @Autowired
    private SellerService sellerService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private UserService userService;
    @Autowired
    private TradeActionMapper tradeActionMapper;
    @Autowired
    private OrderService orderService;
    @RequestMapping("/publishGoods")
    /*
    ******发布商品*******
     *
     */
    public Result publishGoods (@RequestHeader("token") String token,
                           String goodsName,
                           @RequestParam("img") MultipartFile img,
                           String goodsDescription,
                           Float goodsPrice,
                           String goodsType) throws IOException {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode = base64Encoder.encode(img.getBytes());
        Integer status=0;
        MySessionContext myContext = MySessionContext.getInstance();
        HttpSession session = myContext.getSession(token);
        Seller seller=(Seller) session.getAttribute("seller");
        Integer supply_id = (Integer) seller.getId();
        sellerService.publishGoods(goodsName,encode,goodsDescription,goodsPrice,goodsType,status,supply_id);
        return new Result(true,MessageConstant.GOODS_PUBLISH_SUCCESS);
    }
    /*
    ***商家登录*****
    * */
    @RequestMapping("/Sellerlogin")
    public Result Sellerlogin(
                              String account,
                              String password){
        Seller seller = sellerService.Sellerlogin(account);
        if(seller==null){
            return new Result(false,MessageConstant.SELLER_ACCOUNT_NON_EXISTENT);
        }
        else if(!seller.getPassword().equals(password)){
            return new Result(false,MessageConstant.SELLER_PASSWORD_WRONG);
        }
        else{
            HttpSession session = request.getSession();
            session.setAttribute("seller",seller);
            MySessionContext myContext = MySessionContext.getInstance();
            myContext.AddSession(session);
            return new Result(true,MessageConstant.SELLER_LOGIN_SUCCESS,session.getId());
        }
    }
/***********修改密码*******************/
    @RequestMapping("/Passwordupdate")
    public Result Passwordupdate(@RequestHeader("token") String token,String password) {
        MySessionContext myContext = MySessionContext.getInstance();
        HttpSession session = myContext.getSession(token);
        Seller seller=(Seller) session.getAttribute("seller");
        System.out.println(seller.getAccount());
        System.out.println("old密码："+seller.getPassword());
        sellerService.Passwordupdate(seller.getAccount(), password,seller.getPassword());
        return new Result(true,MessageConstant.PASSWORD_UPDATE_SUCCESS);
    }
/*********选择购买人*********/
    @RequestMapping("/checkUser")
    public Result checkUser(Integer id) {
        Integer user_id= tradeActionMapper.trading(id);
        User user=sellerService.checkUser(user_id);
        System.out.println("选择成功");
        return new Result(true,MessageConstant.CHECK_USER_SUCCes,user);
    }

    @RequestMapping("/getLoginUser")
    public Result getLoginUser(@RequestHeader("token") String token){
        MySessionContext myContext = MySessionContext.getInstance();
        HttpSession session = myContext.getSession(token);
        Seller seller=(Seller) session.getAttribute("seller");
        return new Result(true,MessageConstant.GET_USER_SUCCESS,seller);
    }
    @RequestMapping("/logout")
    public Result logout(@RequestHeader("token") String token){
        MySessionContext myContext = MySessionContext.getInstance();
        HttpSession session = myContext.getSession(token);
        myContext.DelSession(session);
        return new Result(true,MessageConstant.LOGOUT_SUCCESS);
    }
    @RequestMapping("/register")
    public Result Register(@RequestBody RegisterParam registerParam){
        System.out.println(registerParam.getAccount());
        sellerService.Register(registerParam.getAccount(),registerParam.getPassword(),registerParam.getName());
        return new Result(true,MessageConstant.REGUSTER_SUCCESS);
    }
    /*******查看意向购买人**********/
    @RequestMapping("/intendingUSer")
    public Result interdingUSer(Integer goods_id){
        List<Buyerinfo> infoList= new ArrayList<>();
        List<User> UserList = new ArrayList<>();
        List<TradeAction> traLIst= sellerService.intendingUser(goods_id);
        for(int i=0;i<traLIst.size();i++){
            UserList.add( sellerService.getintendingUser(traLIst.get(i).getUserId()));
            Buyerinfo bi = new Buyerinfo(UserList.get(i).getName(),traLIst.get(i).getGoodsId(),traLIst.get(i).getId(),UserList.get(i).getTele(),traLIst.get(i).getTradeTime(),traLIst.get(i).getTradePlace());
            infoList.add(bi);
        }
        return new Result(true,MessageConstant.INTENDINGUSER_SUCCESS,infoList);
    }
    /*******选择购买意向人*******/
    @RequestMapping("/chooseUser")
    public Result chooseUSer(Integer id,Integer goods_id){
        sellerService.chooseUser(id,goods_id);
        System.out.println("选择成功");
        return new Result(true,MessageConstant.CHOOSEUSER_SUCCESS);
    }
    /*******注册验证功能*******/
    @RequestMapping("/registerComfirm")
    public Result registerComfirm(){
        boolean flag=sellerService.registerComfirm();
        return new Result(true,MessageConstant.REGISTERCOMFIRM_SUCCESS,flag);
    }
    /********检查是否已经被购买*********/
    @RequestMapping("/checkgoods")
    public Result checkgoods(){
        Integer data=sellerService.checkgoods();
        boolean flag = true;
        if(data==0){
             flag=true;
        }
        else{
             flag=false;
        }
        return new Result(true,MessageConstant.REGISTERCOMFIRM_SUCCESS,flag);
    }
    /*********查看订单数量**********/
    @RequestMapping("/getTradecount")
    public Result getTradecount(Integer goodsId){
        Integer count=sellerService.getTradecount(goodsId);
        return new Result(true,"查看订单数量成功",count);
    }
   /*********修改库存***********/
    @RequestMapping("/reviseStock")
    public Result reviseStock(Integer goodsId){
        Integer stock=sellerService.inquireStock(goodsId);
        if(stock==0){
            return new Result(false,"选择失败，库存为零");
        }
        else{
           sellerService.reviseStock(goodsId);
        return new Result(true,"选择成功");
    }}
    /**********查看已注册用户***********/
    @RequestMapping("/checkUser2")
    public Result checkUser2(){
        List<User> userList=sellerService.checkUser();
        return new Result<>(true,"查看成功",userList);
        }
        /***********查看买家历史订单消息**************/
    @RequestMapping("/seeUsertradition")
    public Result seeUsertradition(Integer user_id){
        List<TradeAction> tradeActionList = sellerService.seeUsertradition(user_id);
        System.out.println(user_id);
        return new Result<>(true,"查看成功",tradeActionList);

        }
    /**********根据订单编号查询订单以及其他信息*********/
    @RequestMapping("/seeTraditionbyid")
    public Result seeTraditionbyid(Integer id){
        TradeAction td = sellerService.seeTraditionbyid(id);
        User u=sellerService.checkUserbyid(td.getUserId());
        Goods g=sellerService.checkgoodbyid(td.getGoodsId());
        allinfo al = new allinfo(td.getId(),td.getTradeTime(), td.getTradePlace(),u.getName(),g.getName(),g.getPrice(),u.getTele());
        System.out.println(al);
        return new Result<>(true,"查看成功",al);

    }
    /*********根据id查用户信息************/
    @RequestMapping("/checkUserbyid")
    public Result checkUserbyid(Integer id){
        User u=sellerService.checkUserbyid(id);
        System.out.println(u.getId()+u.getDefaultTraderPlace());
        List<User> ul =new ArrayList<User>();
        ul.add(u);
        return new Result<>(true,"查看成功",ul);

    }
    /***********查看历史商品*****************/
    @RequestMapping("/seehistoricalgoods")
    public Result seehistoricalgoods(){
        List<Goods> goodsList=sellerService.seehistoricalgoods();
        return new Result<>(true,"查看成功",goodsList);
    }
    /**********未完成交易商品*************/
    @RequestMapping("/goodsnotbuy")
    public Result goodsnotbuy(){
        List<Goods> goodsList=sellerService.goodsnotbuy();

        return new Result<>(true,"查看成功",goodsList);
    }
    /************自动下架**********/
    @RequestMapping("/Automaticdismounting")
    public Result Automaticdismounting(Integer id){
        sellerService.Automaticdismounting(id);
        return new Result<>(true,"查看成功");
    }

    /**
     * 第二版的发布商品
     * @param token
     * @param goodsName
     * @param file
     * @param goodsDescription
     * @param goodsPrice
     * @param goodsType
     * @return
     * @throws IOException
     */
    @RequestMapping("/publishGoods2")
    public Result publishGoods2 (@RequestHeader("token") String token,
                                String goodsName,
                                @RequestParam("file") MultipartFile[] file,
                                String goodsDescription,
                                Float goodsPrice,
                                String goodsType,
                                 Integer stock,
                                 String select) throws IOException {
        List<String> encodes = new ArrayList<>();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        for(int i=0;i<file.length;i++){
            String encode = base64Encoder.encode(file[i].getBytes());
            encodes.add(encode);
        }
        Integer status=0;
        MySessionContext myContext = MySessionContext.getInstance();
        HttpSession session = myContext.getSession(token);
        Seller seller=(Seller) session.getAttribute("seller");
        Integer supply_id = seller.getId();
        sellerService.publishGoods2(goodsName,encodes,goodsDescription,goodsPrice,goodsType,status,supply_id,stock,select);
        return new Result(true,MessageConstant.GOODS_PUBLISH_SUCCESS);
    }
    /************下架商品**********/
    @RequestMapping("/DownGoods")
    public Result DownGoods(String name){
        sellerService.DownGoods(name);
        return new Result<>(true,"下架商品成功");
    }
    /**********完成订单**********/
    @RequestMapping("/completeGoods")
    public Result completeGoods(Integer id){
        sellerService.completeGoods(id);
        return new Result<>(true,"订单已完成");
    }


    //此后为新增
    /************取消订单**********/
    @RequestMapping("/CancelTrad")
    public Result CancelTrad(Integer id, Integer goodsid){
        System.out.println("成功");
        sellerService.CancelTrad(id);
        Integer stock=sellerService.inquireStock(goodsid);
        if(stock==0){
            sellerService.UpGoods(goodsid);
        }
        sellerService.AddStock(goodsid);
        return new Result<>(true,"取消成功");
    }

    /************根据订单id将订单状态从确认订单变更为待发货**********/
    @RequestMapping("/prepareTheGoods")
    public Integer PrepareTheGoods(Integer tradeid){
        return sellerService.prepareTheGoods(tradeid);
    }

    /************根据订单id将订单状态从待发货变更为已发货**********/
    @RequestMapping("/prepareFineWaitingforSendOut")
    public Integer PrepareFineWatingforSendOut(Integer tradeid){
        return sellerService.prepareFineWatingforSendOut(tradeid);
    }
    /************根据订单编号将订单状态从确认订单变更为待发货**********/
    @RequestMapping("/prepareTheGoodsByTradeNo")
    public Integer PrepareTheGoodsByTradeNo(String tradeNo){
        return tradeActionMapper.prepareTheGoodsByTradeNo(tradeNo);
    }

    /************根据订单编号将订单状态从待发货变更为已发货**********/
    @RequestMapping("/prepareFineWaitingforSendOutByTradeNo")
    public Integer PrepareFineWatingforSendOutByTradeNo(String tradeNo){
        return  tradeActionMapper.prepareFineWatingforSendOutByTradeNo(tradeNo);
    }
    /************取消订单**********/
    @RequestMapping("/CancelTrad2")
    public Result CancelTrad2(Integer id, Integer goodsid){
        System.out.println("成功");
        int num = orderService.getTradeNum(id);
        //System.out.println(num);
        Integer stock=sellerService.inquireStock(goodsid);
        if(stock==0){
            sellerService.UpGoods(goodsid);
        }
        userService.CancelTrade(id);
        sellerService.AddStock2(goodsid,num);
        return new Result<>(true,"取消成功");
    }
    /************根据订单编号取消订单**********/
    @RequestMapping("/CancelTradByTradeNo")
    public Result CancelTradByTradeNo(String tradeNo){
        List<Integer> tradeidList = tradeActionMapper.getTradeIdByTradeNo(tradeNo);
        //System.out.println(tradeidList);
        List<Integer> goodidList = tradeActionMapper.getGoodIdByTradeNo(tradeNo);
        //System.out.println(goodidList);
        for (int i=0;i<tradeidList.size();i++){
            int tradeid = tradeidList.get(i);
            int goodid = goodidList.get(i);
            int num = orderService.getTradeNum(tradeid);
            int stock =sellerService.inquireStock(goodid);
            if(stock==0){
                sellerService.UpGoods(goodid);
            }
            userService.CancelTrade(tradeid);
            sellerService.AddStock2(goodid,num);
        }
        return new Result<>(true,"取消成功");
    }
}
